package org.thunms.framework.views;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang3.StringUtils;
/**
 * 文本截取标签
 * @author wanglp
 *
 */
public class TextCutTag extends TagSupport {
	private static final long serialVersionUID = 5233933923291880013L;
	private String textString;
	private Integer maxLength=25;
	private String append;
	
	@Override
	public int doStartTag() throws JspException {
		try {
			StringBuffer head = new StringBuffer();
			if (textString != null) {
				int slen = textString.length();
				if (slen <= maxLength) {
					head.append(textString);
				}else{
					// 最大计数（如果全是英文）
					int maxCount = maxLength * 2;
					int count = 0;
					int i = 0;
					for (; count < maxCount && i < slen; i++) {
						if (textString.codePointAt(i) < 256) {
							count++;
						} else {
							count += 2;
						}
					}
					if (i < slen) {
						if (count > maxCount) {
							i--;
						}
						if (!StringUtils.isBlank(append)) {
							if (textString.codePointAt(i - 1) < 256) {
								i -= 2;
							} else {
								i--;
							}
							head.append(textString.substring(0, i) + append) ;
						} else {
							head.append(textString.substring(0, i)) ;
						}
					} else {
						head.append(textString);
					}
				}
			}
			JspWriter out = this.pageContext.getOut();
			out.print(head.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}

		return SKIP_BODY;
	}

	

	public String getTextString() {
		return textString;
	}



	public void setTextString(String textString) {
		this.textString = textString;
	}



	public Integer getMaxLength() {
		return maxLength;
	}

	public void setMaxLength(Integer maxLength) {
		this.maxLength = maxLength;
	}

	public String getAppend() {
		return append;
	}

	public void setAppend(String append) {
		this.append = append;
	}
	
}
